<template>
<div class="search-container">
    <!-- 搜索头部 -->
    <div class="search-header">
        <van-icon name="arrow-left" class="back-icon" @click="$router.back()" />
        <van-search v-model="searchValue" placeholder="搜索笔记/用户/话题" shape="round" show-action @search="onSearch"
            @cancel="onCancel" @focus="onFocus" @clear="onClear" />
    </div>

    <!-- 搜索历史和热门搜索 -->
    <div class="search-history" v-if="!searchValue && !searching">
        <!-- 搜索历史 -->
        <div class="history-section" v-if="searchHistory.length > 0">
            <div class="section-header">
                <div class="section-title">搜索历史</div>
                <van-icon name="delete" @click="clearHistory" />
            </div>
            <div class="history-list">
                <div v-for="(item, index) in searchHistory" :key="index" class="history-item"
                    @click="searchByHistory(item)">
                    <van-icon name="clock-o" />
                    <span>{{ item }}</span>
                </div>
            </div>
        </div>

        <!-- 热门搜索 -->
        <div class="hot-section">
            <div class="section-header">
                <div class="section-title">热门搜索</div>
            </div>
            <div class="hot-list">
                <div v-for="(item, index) in hotSearches" :key="index" class="hot-item"
                    :class="{ 'hot-top': index < 3 }" @click="searchByHot(item)">
                    <div class="hot-rank">{{ index + 1 }}</div>
                    <div class="hot-info">
                        <div class="hot-keyword">{{ item.keyword }}</div>
                        <div class="hot-tag" v-if="item.tag">{{ item.tag }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 搜索建议 -->
    <div class="search-suggest" v-if="searchValue && !searching">
        <div v-for="(item, index) in searchSuggestions" :key="index" class="suggest-item"
            @click="searchBySuggest(item)">
            <van-icon name="search" />
            <span v-html="highlightKeyword(item)"></span>
        </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-result" v-if="searching">
        <van-tabs v-model="activeTab" sticky swipeable animated>
            <van-tab title="综合">
                <!-- 综合搜索结果 -->
                <div class="result-list" v-if="searchResults.comprehensive.length > 0">
                    <div v-for="(item, index) in searchResults.comprehensive" :key="index" class="result-item"
                        @click="goToDetail(item.id)">
                        <div class="result-cover">
                            <img :src="item.cover" :alt="item.title" />
                            <div class="result-type" v-if="item.type === 'video'">
                                <van-icon name="play-circle-o" />
                            </div>
                        </div>
                        <div class="result-info">
                            <div class="result-title" v-html="highlightKeyword(item.title)"></div>
                            <div class="result-desc" v-html="highlightKeyword(item.desc)"></div>
                            <div class="result-stats">
                                <span class="result-user">
                                    <img :src="item.userAvatar" :alt="item.userName" />
                                    {{ item.userName }}
                                </span>
                                <span class="result-like">
                                    <van-icon name="like-o" />
                                    {{ item.likes }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-else class="empty-result">
                    <van-empty description="暂无相关内容" />
                </div>
            </van-tab>

            <van-tab title="笔记">
                <!-- 笔记搜索结果 -->
                <div class="result-grid" v-if="searchResults.notes.length > 0">
                    <div v-for="(item, index) in searchResults.notes" :key="index" class="grid-item"
                        @click="goToDetail(item.id)">
                        <div class="grid-cover">
                            <img :src="item.cover" :alt="item.title" />
                            <div class="grid-type" v-if="item.type === 'video'">
                                <van-icon name="play-circle-o" />
                            </div>
                        </div>
                        <div class="grid-title" v-html="highlightKeyword(item.title)"></div>
                        <div class="grid-user">
                            <img :src="item.userAvatar" :alt="item.userName" />
                            <span>{{ item.userName }}</span>
                        </div>
                    </div>
                </div>
                <div v-else class="empty-result">
                    <van-empty description="暂无相关笔记" />
                </div>
            </van-tab>

            <van-tab title="用户">
                <!-- 用户搜索结果 -->
                <div class="user-list" v-if="searchResults.users.length > 0">
                    <div v-for="(item, index) in searchResults.users" :key="index" class="user-item"
                        @click="goToUser(item.id)">
                        <div class="user-avatar">
                            <img :src="item.avatar" :alt="item.nickname" />
                        </div>
                        <div class="user-info">
                            <div class="user-name" v-html="highlightKeyword(item.nickname)"></div>
                            <div class="user-desc">{{ item.description }}</div>
                            <div class="user-stats">
                                <span>笔记 {{ item.postCount }}</span>
                                <span>粉丝 {{ item.fansCount }}</span>
                            </div>
                        </div>
                        <div class="follow-btn" :class="{ 'followed': item.isFollowed }"
                            @click.stop="toggleFollow(index)">
                            {{ item.isFollowed ? '已关注' : '关注' }}
                        </div>
                    </div>
                </div>
                <div v-else class="empty-result">
                    <van-empty description="暂无相关用户" />
                </div>
            </van-tab>

            <van-tab title="话题">
                <!-- 话题搜索结果 -->
                <div class="topic-list" v-if="searchResults.topics.length > 0">
                    <div v-for="(item, index) in searchResults.topics" :key="index" class="topic-item"
                        @click="goToTopic(item.id)">
                        <div class="topic-cover">
                            <img :src="item.cover" :alt="item.name" />
                        </div>
                        <div class="topic-info">
                            <div class="topic-name" v-html="highlightKeyword(item.name)"></div>
                            <div class="topic-stats">
                                <span>{{ item.postCount }}篇笔记</span>
                                <span>{{ item.viewCount }}次浏览</span>
                            </div>
                        </div>
                        <van-icon name="arrow" class="topic-arrow" />
                    </div>
                </div>
                <div v-else class="empty-result">
                    <van-empty description="暂无相关话题" />
                </div>
            </van-tab>
        </van-tabs>
    </div>
</div>
</template>

<script>
export default {
    name: 'SearchPage',

    data() {
        return {
            searchValue: '',
            searching: false,
            activeTab: 0,

            // 搜索历史
            searchHistory: ['咖啡', '旅行', '美食', '穿搭'],

            // 热门搜索
            hotSearches: [
                { keyword: '夏日穿搭', tag: '热门' },
                { keyword: '咖啡店打卡', tag: '上升' },
                { keyword: '复古风', tag: '新晋' },
                { keyword: '健身餐', tag: '' },
                { keyword: '手工DIY', tag: '' },
                { keyword: '城市摄影', tag: '' },
                { keyword: '读书笔记', tag: '' },
                { keyword: '家居布置', tag: '' }
            ],

            // 搜索建议
            searchSuggestions: [],

            // 搜索结果
            searchResults: {
                comprehensive: [],
                notes: [],
                users: [],
                topics: []
            }
        }
    },

    watch: {
        searchValue(val) {
            if (val) {
                this.getSearchSuggestions(val)
            } else {
                this.searchSuggestions = []
                this.searching = false
            }
        }
    },

    methods: {
        // 搜索操作
        onSearch() {
            if (!this.searchValue.trim()) return

            this.searching = true
            this.addToHistory(this.searchValue)
            this.fetchSearchResults(this.searchValue)
        },

        // 取消搜索
        onCancel() {
            this.$router.back()
        },

        // 输入框获取焦点
        onFocus() {
            this.searching = false
        },

        // 清空输入框
        onClear() {
            this.searching = false
            this.searchSuggestions = []
        },

        // 清空历史记录
        clearHistory() {
            this.$dialog.confirm({
                title: '提示',
                message: '确定要清空搜索历史吗？',
            }).then(() => {
                this.searchHistory = []
                this.$toast('已清空搜索历史')
            })
        },

        // 通过历史记录搜索
        searchByHistory(keyword) {
            this.searchValue = keyword
            this.onSearch()
        },

        // 通过热门搜索
        searchByHot(item) {
            this.searchValue = item.keyword
            this.onSearch()
        },

        // 通过搜索建议搜索
        searchBySuggest(keyword) {
            this.searchValue = keyword
            this.onSearch()
        },

        // 添加到搜索历史
        addToHistory(keyword) {
            // 如果已存在，先移除
            const index = this.searchHistory.indexOf(keyword)
            if (index > -1) {
                this.searchHistory.splice(index, 1)
            }

            // 添加到最前面
            this.searchHistory.unshift(keyword)

            // 最多保留10条
            if (this.searchHistory.length > 10) {
                this.searchHistory.pop()
            }
        },

        // 获取搜索建议
        getSearchSuggestions(keyword) {
            // 模拟搜索建议
            const suggestions = [
                keyword,
                `${keyword}推荐`,
                `${keyword}攻略`,
                `${keyword}教程`,
                `${keyword}分享`
            ]

            this.searchSuggestions = suggestions
        },

        // 获取搜索结果
        fetchSearchResults(keyword) {
            // 模拟搜索请求
            setTimeout(() => {
                // 综合结果
                this.searchResults.comprehensive = Array.from({ length: 5 }, (_, i) => {
                    return {
                        id: i + 1,
                        title: `${keyword}相关笔记 ${i + 1}`,
                        desc: `这是一篇关于${keyword}的精彩笔记，包含了很多实用的信息和技巧...`,
                        cover: `https://picsum.photos/300/400?random=${i + 100}`,
                        type: Math.random() > 0.7 ? 'video' : 'image',
                        userName: `用户${Math.floor(Math.random() * 1000)}`,
                        userAvatar: `https://i.pravatar.cc/100?u=${i + 200}`,
                        likes: Math.floor(Math.random() * 1000)
                    }
                })

                // 笔记结果
                this.searchResults.notes = Array.from({ length: 10 }, (_, i) => {
                    return {
                        id: i + 100,
                        title: `${keyword}笔记 ${i + 1}`,
                        cover: `https://picsum.photos/300/400?random=${i + 300}`,
                        type: Math.random() > 0.7 ? 'video' : 'image',
                        userName: `用户${Math.floor(Math.random() * 1000)}`,
                        userAvatar: `https://i.pravatar.cc/100?u=${i + 400}`
                    }
                })

                // 用户结果
                this.searchResults.users = Array.from({ length: 8 }, (_, i) => {
                    return {
                        id: i + 200,
                        nickname: `${keyword}用户${i + 1}`,
                        avatar: `https://i.pravatar.cc/100?u=${i + 500}`,
                        description: `热爱${keyword}的生活达人，分享${keyword}相关内容`,
                        postCount: Math.floor(Math.random() * 100),
                        fansCount: Math.floor(Math.random() * 10000),
                        isFollowed: Math.random() > 0.7
                    }
                })

                // 话题结果
                this.searchResults.topics = Array.from({ length: 6 }, (_, i) => {
                    return {
                        id: i + 300,
                        name: `${keyword}${['生活', '攻略', '分享', '教程', '推荐', '达人'][i % 6]}`,
                        cover: `https://picsum.photos/100/100?random=${i + 600}`,
                        postCount: Math.floor(Math.random() * 10000),
                        viewCount: Math.floor(Math.random() * 1000000)
                    }
                })
            }, 500)
        },

        // 高亮关键词
        highlightKeyword(text) {
            if (!this.searchValue || !text) return text

            const reg = new RegExp(this.searchValue, 'gi')
            return text.replace(reg, match => `<span class="highlight">${match}</span>`)
        },

        // 关注/取消关注用户
        toggleFollow(index) {
            const user = this.searchResults.users[index]
            user.isFollowed = !user.isFollowed

            this.$toast(user.isFollowed ? '已关注' : '已取消关注')
        },

        // 跳转到详情页
        goToDetail(id) {
            this.$router.push(`/detail/${id}`)
        },

        // 跳转到用户页
        goToUser(id) {
            this.$router.push(`/user/${id}`)
        },

        // 跳转到话题页
        goToTopic(id) {
            this.$toast(`话题页面开发中，话题ID: ${id}`)
        }
    }
}
</script>

<style scoped>
.search-container {
    min-height: 100vh;
    background-color: var(--color-white);
}

.search-header {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    background-color: var(--color-white);
    position: sticky;
    top: 0;
    z-index: 100;
}

.back-icon {
    margin-right: 8px;
    font-size: 20px;
}

.search-header :deep(.van-search) {
    flex: 1;
    padding: 0;
}

.search-header :deep(.van-search__content) {
    background-color: var(--color-background);
}

.search-history {
    padding: 16px;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.section-title {
    font-size: var(--font-size-medium);
    font-weight: var(--font-weight-medium);
}

.history-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 24px;
}

.history-item {
    display: flex;
    align-items: center;
    padding: 6px 12px;
    background-color: var(--color-background);
    border-radius: 16px;
    font-size: var(--font-size-small);
}

.history-item .van-icon {
    margin-right: 4px;
    color: var(--color-text-secondary);
}

.hot-list {
    margin-bottom: 16px;
}

.hot-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid var(--color-border);
}

.hot-rank {
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    font-weight: var(--font-weight-bold);
    color: var(--color-text-secondary);
}

.hot-top .hot-rank {
    color: var(--color-primary);
}

.hot-info {
    flex: 1;
    display: flex;
    align-items: center;
}

.hot-keyword {
    font-size: var(--font-size-normal);
    margin-right: 8px;
}

.hot-tag {
    padding: 2px 6px;
    background-color: rgba(255, 36, 66, 0.1);
    color: var(--color-primary);
    border-radius: 4px;
    font-size: var(--font-size-mini);
}

.search-suggest {
    padding: 0 16px;
}

.suggest-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid var(--color-border);
}

.suggest-item .van-icon {
    margin-right: 12px;
    color: var(--color-text-secondary);
}

.search-result {
    min-height: calc(100vh - 54px);
}

.result-list {
    padding: 12px 16px;
}

.result-item {
    display: flex;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--color-border);
}

.result-cover {
    position: relative;
    width: 120px;
    height: 120px;
    border-radius: var(--border-radius-small);
    overflow: hidden;
    margin-right: 12px;
}

.result-cover img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.result-type {
    position: absolute;
    top: 8px;
    right: 8px;
    color: white;
    font-size: 24px;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.result-info {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.result-title {
    font-size: var(--font-size-medium);
    font-weight: var(--font-weight-medium);
    margin-bottom: 8px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.result-desc {
    font-size: var(--font-size-small);
    color: var(--color-text-secondary);
    margin-bottom: 8px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    flex: 1;
}

.result-stats {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: var(--font-size-small);
    color: var(--color-text-secondary);
}

.result-user {
    display: flex;
    align-items: center;
}

.result-user img {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    margin-right: 4px;
}

.result-like {
    display: flex;
    align-items: center;
}

.result-like .van-icon {
    margin-right: 4px;
}

.result-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
    padding: 12px 8px;
}

.grid-item {
    margin-bottom: 16px;
}

.grid-cover {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 100%;
    border-radius: var(--border-radius-small);
    overflow: hidden;
    margin-bottom: 8px;
}

.grid-cover img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.grid-type {
    position: absolute;
    top: 8px;
    right: 8px;
    color: white;
    font-size: 24px;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.grid-title {
    font-size: var(--font-size-small);
    margin-bottom: 4px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    height: 2.8em;
}

.grid-user {
    display: flex;
    align-items: center;
    font-size: var(--font-size-mini);
    color: var(--color-text-secondary);
}

.grid-user img {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    margin-right: 4px;
}

.user-list {
    padding: 12px 16px;
}

.user-item {
    display: flex;
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px solid var(--color-border);
}

.user-avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 12px;
}

.user-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.user-info {
    flex: 1;
}

.user-name {
    font-size: var(--font-size-normal);
    font-weight: var(--font-weight-medium);
    margin-bottom: 4px;
}

.user-desc {
    font-size: var(--font-size-small);
    color: var(--color-text-secondary);
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
}

.user-stats {
    font-size: var(--font-size-mini);
    color: var(--color-text-secondary);
}

.user-stats span {
    margin-right: 8px;
}

.follow-btn {
    padding: 6px 16px;
    border-radius: 16px;
    background-color: var(--color-primary);
    color: var(--color-white);
    font-size: var(--font-size-small);
}

.follow-btn.followed {
    background-color: var(--color-background);
    color: var(--color-text-secondary);
}

.topic-list {
    padding: 12px 16px;
}

.topic-item {
    display: flex;
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px solid var(--color-border);
}

.topic-cover {
    width: 50px;
    height: 50px;
    border-radius: var(--border-radius-small);
    overflow: hidden;
    margin-right: 12px;
}

.topic-cover img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.topic-info {
    flex: 1;
}

.topic-name {
    font-size: var(--font-size-normal);
    font-weight: var(--font-weight-medium);
    margin-bottom: 4px;
}

.topic-stats {
    font-size: var(--font-size-mini);
    color: var(--color-text-secondary);
}

.topic-stats span {
    margin-right: 8px;
}

.topic-arrow {
    color: var(--color-text-secondary);
}

.empty-result {
    padding: 40px 0;
}

.highlight {
    color: var(--color-primary);
}

/* 修改Vant样式 */
:deep(.van-tabs__line) {
    background-color: var(--color-primary);
}

:deep(.van-tab--active) {
    color: var(--color-primary);
}
</style>